package com.lin.project.lininit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.lin.project.lininit.common.BaseResponse;
import com.lin.project.lininit.common.DeleteRequest;
import com.lin.project.lininit.common.ErrorCode;
import com.lin.project.lininit.common.ResultUtils;
import com.lin.project.lininit.exception.BusinessException;
import com.lin.project.lininit.model.dto.user.*;
import com.lin.project.lininit.model.entity.User;
import com.lin.project.lininit.model.vo.UserVO;
import com.lin.project.lininit.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@ApiSupport(author = "linhuaixu@126.com",order = 284)
public class UserController {
    @Resource
    private UserService userService;

    private static final String SALT="linhuaixu";

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if(userRegisterRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if(StringUtils.isAnyBlank(userPassword,userAccount,checkPassword)){
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     *
     *
     * @description: 用户登录
     * @param userLoginRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if(userLoginRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAnyBlank(userPassword,userAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     *
     *
     * @description: 用户注销
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     *
     *
     * @description: 获取当前登录用户
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 17:03
     */

    @GetMapping("/get/login")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(loginUser,userVO);
        return ResultUtils.success(userVO);
    }

    /**
     *
     *
     * @description: 用户添加
     * @param userAddRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest){
        if(userAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String encryptPassword="";
        if(userAddRequest.getUserPassword()!=null){
            if(userAddRequest.getUserPassword().length()<8){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8");
            }
            //2.加密
            encryptPassword= DigestUtils.md5DigestAsHex((SALT+userAddRequest.getUserPassword()).getBytes());
        }
        User user=new User();
        BeanUtils.copyProperties(userAddRequest,user);
        user.setUserPassword(encryptPassword);
        boolean save = userService.save(user);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(user.getId());
    }

    /**
     *
     *
     * @description: 用户删除
     * @param deleteRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 用户更新
     * @param userUpdateRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest){
        if(userUpdateRequest==null || userUpdateRequest.getId()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String encryptPassword="";
        if(userUpdateRequest.getUserPassword()!=null){
            if(userUpdateRequest.getUserPassword().length()<8){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8");
            }
            //2.加密
            encryptPassword= DigestUtils.md5DigestAsHex((SALT+userUpdateRequest.getUserPassword()).getBytes());
        }
        User user=new User();
        BeanUtils.copyProperties(userUpdateRequest,user);
        if(!encryptPassword.equals("")){
            user.setUserPassword(encryptPassword);
        }
        boolean b = userService.updateById(user);
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 根据id获取用户
     * @param id
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @GetMapping("/get")
    public BaseResponse<UserVO> getUserById(int id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }

    /**
     *
     *
     * @description: 获取用户列表
     * @param userQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @GetMapping("/list")
    public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest){
        User user=new User();
        if(userQueryRequest!=null){
            BeanUtils.copyProperties(userQueryRequest,user);
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>(user);
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> userVOList=userList.stream().map(user1 -> {
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user1,userVO);
            return userVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(userVOList);
    }

    /**
     *
     *
     * @description: 分页获取用户列表
     * @param userQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/15 16:13
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        long current = 1;
        long size = 10;
        User userQuery = new User();
        if (userQueryRequest != null) {
            BeanUtils.copyProperties(userQueryRequest, userQuery);
            current = userQueryRequest.getCurrent();
            size = userQueryRequest.getPageSize();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        Page<UserVO> userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }
}
